package com.bee.beemanage.system.aspect.filters;

import com.alibaba.fastjson.JSON;
import com.bee.beemanage.api.entity.SysUser;
import com.bee.beemanage.api.entity.token.TokenDetail;
import com.bee.beemanage.system.common.exceptions.ErrorTokenException;
import com.bee.beemanage.system.common.utils.redis.RedisUtils;
import com.bee.beemanage.system.common.utils.result.Result;
import com.bee.beemanage.system.common.utils.result.ResultCode;
import com.bee.beemanage.system.common.utils.result.ResultTool;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author 陈国松
 * @createTime 2022/8/17 14:37
 * @description
 */
@Component
public class TokenFilter extends OncePerRequestFilter {

    /**
     * 获取登录请求地址
     */
    @Value("${token.tokenIgnore}")
    private String tokenIgnore;

    @Resource
    private RedisUtils redisUtils;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取请求的url
        String url = request.getRequestURI();
        boolean tokenIgnoreFlag = true;
        String[] split = tokenIgnore.split(",");
        for (String s : split) {
            if(url.contains(s)){
                tokenIgnoreFlag = false;
            }
        }
        System.out.println(tokenIgnoreFlag+":"+url);
        //需要认证的
        if (tokenIgnoreFlag) {
            String tokeninfo = request.getHeader("Authorization");
            Result result = new Result();
            if(tokeninfo!=null){
                try {
                    String bearer = tokeninfo.replace("Bearer ", "");
                    String tokenInfo = (String) redisUtils.get("LoginUsers:"+bearer);
                    TokenDetail tokenDetail = JSON.parseObject(tokenInfo,TokenDetail.class);
                    if(tokenDetail==null){
                        throw new ErrorTokenException();
                    }
                    String[] tokenAuthorities = tokenDetail.getAuthorities().toString().split(",");
                    SysUser user = tokenDetail.getUser();
                    System.out.println(user);
                    StringBuilder as = new StringBuilder();
                    for (String s : tokenAuthorities) {
                        as.append(s).append(",");
                    }
                    //获取当前登录用户名
                    List<GrantedAuthority> authorities = AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(as));
                    UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(user, null, authorities);
                    SecurityContextHolder.getContext().setAuthentication(token);
                    filterChain.doFilter(request,response);
                }catch (ErrorTokenException e) {
                    result = ResultTool.fail(ResultCode.TOKEN_ERROR);
                    response.setContentType("text/json;charset=utf-8");
                    response.getWriter().write(JSON.toJSONString(result));
                }
            }else{
                result = ResultTool.fail(ResultCode.USER_NOT_LOGIN);
                response.setContentType("text/json;charset=utf-8");
                response.getWriter().write(JSON.toJSONString(result));
            }
        } else {
            //不需要验证token
            doFilter(request, response, filterChain);
        }
    }
}